#include "link.h"

SOCK_NODE *link_head_create(void)
{
	SOCK_NODE *head = NULL;

	head = (SOCK_NODE *)malloc(sizeof(SOCK_NODE));
	if(head == NULL){
		perror("malloc error.");
		return NULL;
	}
	head->next = NULL;

	return head;
}

void link_node_connect(SOCK_NODE *head, SOCK_NODE *pi)
{
	SOCK_NODE *p = head;

	while(p->next != NULL){
		p = p->next;
	}
	p->next = pi;
	pi->next = NULL;
}

INT32 malloc_node_num(SOCK_NODE *head, INT32 n, SOCK_NODE *p)
{
	SOCK_NODE *pi = NULL;
	INT32 ix;
	for(ix = 0; ix < n; ix++){
		pi = (SOCK_NODE *)malloc(sizeof(SOCK_NODE));
		if(pi == NULL){
			perror("malloc().");
			return -1;
		}
		pi->sfd = p->sfd;
		memcpy(pi->sim, p->sim, 12);
		link_node_connect(head, pi);
	}
	return 0;
}


INT32 link_node_delet(SOCK_NODE *head, INT32 sfd)
{
	SOCK_NODE *p = head, *pf = NULL;

	while(p != NULL){
		if(p->sfd != sfd){
			pf = p;
			p = p->next;
		}
		else
			break;
	}
	if(p == NULL)
		return -1;
	else{
		pf->next = p->next;
		free(p);
	}
	return 0;
}

INT32 link_sim_search(SOCK_NODE *head, INT8 *pIn)
{
	SOCK_NODE *p = head;

	if(head == NULL || pIn == NULL)
		return -1;
	while(p != NULL){
		if(strncmp(p->sim, pIn, 11))
			p = p->next;
		else
			break;
	}
	if(p == NULL)
		return 0;
	else
		return (p->sfd);
}

INT32 link_sfd_search(SOCK_NODE *head, INT32 fd, INT8 *pIn)
{
	SOCK_NODE *p = head;

	if(head == NULL || pIn == NULL)
		return -1;
	while(p != NULL){
		if(p->sfd != fd)
			p = p->next;
		else
			break;
	}
	if(p == NULL)
		return -1;
	else{
		memcpy(pIn, p->sim, 11);
	}
		return 0;
}

void link_destory(SOCK_NODE *head)
{
	SOCK_NODE *p = head, *pf = NULL;

	while(p != NULL){
		pf = p;
		p = p->next;
		free(pf);
	}
}

void link_node_print(SOCK_NODE *head)
{
         SOCK_NODE *p = head -> next;
 
         while(p != NULL){
 
                 printf("sfd: %d sim: %s\n", p->sfd, p->sim);
                 p = p -> next;
         }
}

